package com.foton.bpc.all.serialzation.json;

import com.foton.bpc.all.serialzation.Serialzation;

import java.io.*;

/**
 * @Author RenPu
 * @Date 2023/6/5 15:11
 * @Version 1.0
 * @Description:
 **/
public class JsonSerialzation implements Serialzation {


    /**
     * 客户端： java object --->  byte[]
     * @param obj
     * @return
     * @throws Exception
     */
    @Override
    public byte[] serialzation(Object obj) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.flush();
        byte[] data = bos.toByteArray();
        oos.close();
        bos.close();
        return data;
    }




    /**
     * 服务端： byte[] ---> java object
     * @param parm
     * @param clazz
     * @return
     * @throws Exception
     * java.io.StreamCorruptedException: invalid stream header: 74737400
     * 解决博客：https://blog.csdn.net/weixin_44142151/article/details/124188691
     */
    @Override
    public Object derialzation(byte[] parm, Class clazz) throws Exception {
        ByteArrayInputStream bis = new ByteArrayInputStream(parm);
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object obj = ois.readObject();
        return obj;
    }
}



